package com.shiguiwu.springmybatis.netty.simple.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: 客户端处理器
 * @author: stone
 * @date: Created by 2021/12/5 19:12
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.netty.simple.handler
 */
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当通道就绪时会触发该方法
     *
     * @param ctx 上下文
     * @throws Exception e
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("client ok maimai");
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello server my is client".getBytes(CharsetUtil.UTF_8)));
    }

    /**
     * 当通道有读取事件的时候，会触发该方法！！！
     *
     * @param ctx 上下文
     * @param msg 消息本身
     * @throws Exception e
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        log.info("server is msg ==> {}" , byteBuf.toString(CharsetUtil.UTF_8));

        log.info("server is ip address ==> {}" , ctx.channel().remoteAddress());

    }

    /**
     * 当发生异常的时候，会触发这个方法！！
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("通道发生异常 ===> {}", cause.getMessage());
        ctx.close();
    }
}
